// vbmcgi_VBPageCount.cpp

#include <fstream>
#include "VBMcgi/VBMcgi.h"
#include "VBMcgi/VBPageCount.h"


using namespace br::com::sbVB::VBLib;
using namespace std;


void br::com::sbVB::VBMcgi::VBPageCount::putData(ostream & out, const char *id, int data) 
{
	// cout << "DEBUG:" << id << m_token << data << endl;
	out << id << m_token << data << endl;
}

br::com::sbVB::VBMcgi::VBPageCount::VBPageCount(const char *id, bool increment, const char*fileName) 
{
	privateConstructor (id,fileName,increment);
}

br::com::sbVB::VBMcgi::VBPageCount::VBPageCount(const char *id, const char*fileName) 
{
	privateConstructor(id,fileName,true);
}

void br::com::sbVB::VBMcgi::VBPageCount::privateConstructor(const char *id, const char*fileName,bool increment) 
{
	m_token = ';';
	m_count = 1;

	ifstream iFile(fileName);
	bool existFile = (iFile != 0);
	iFile.close();
	if (!existFile) 
	{
		// cout << "DEBUG: first time creating file" << endl;
		ofstream oFile(fileName);
		if (!oFile) 
		{
			// The software couldn't open a file for writing. 
			// This could be due to non usage of su_exec, or other problems.
			// Be careful to send a notice to the file user here, because
			// the absence of a html header can cause a "Internal Server Error"
		}
		putData (oFile,id,1);
		oFile.close();
		return;
	}
	// file already exists, so look for existence of id.
	VBString s;
	VBString auxFileName = fileName;
	auxFileName += "___";
	iFile.open(fileName);
	// if (!iFile) cout << "DEBUG: iFile not open" << endl;
	ofstream auxoFile(auxFileName);
	// if (!auxoFile) cout << "DEBUG: auxoFile not open" << endl;
	bool found = false;
	do {
		iFile >> s;
		if (iFile.eof()) break;
		// cout << "DEBUG: " << s << endl;
		VBString current_id = s.strtok(m_token,0);
		if (current_id == VBString(id)) {
			found = true;
			m_count = atoi(s.strtok(m_token,1));
			if (increment)
				m_count++; // increments the count
			// cout << "DEBUG: m_count" << m_count << endl;
			putData (auxoFile,id,m_count);
		}
		else {
			auxoFile << s << endl; // simply copy the string the auxiliary file
		}
	} while (!iFile.eof());
	iFile.close();
	
	if (found) {
		// cout << "DEBUG: file exists, id exists. I incremented the id in the file" << endl;
		remove (fileName);
		rename (auxFileName, fileName);
	}
	// if there is no id in the given data file, than this is the first 
	// time this id is going to be saved
	else {
		// cout << "DEBUG: file exists, but this is the first time for this id" << endl;
		ofstream oFile(fileName,ios::app); // open the file to append something at the end of it
		putData (oFile,id,1);
		oFile.close();
	}
}

VBString br::com::sbVB::VBMcgi::VBPageCount::getCount() 
{
	VBString ret;
	ret += m_count;
	// cout << "DEBUG: m_count" << m_count << endl;
	return ret;
}


